<?php
class ManagerController extends AppController {
    public $helpers = array('Html', 'Form', 'Navigation');
    public $name = 'Manager';
    var $components = array('CAS_Auth','Session', 'Navigation');
    //models used by this controller
    var $uses = array('Manager','Hour','Group','Employee','Project', 'Request');

    public function beforeFilter(){
    		parent::beforeFilter();

		$this->CAS_Auth->checkAuthentication();
		$this->account = $this->CAS_Auth->getGTAccount();
		$this->set('gtAccount', $this->account);
		
		//use authentication to display appropriate menu
		$this->permissions = array();
		if($this->setupMgr($this->account))
			$this->permissions[] = 'manager';
		else
			$this->redirect('/');
		if($this->Employee->find('count', array('conditions'=> array('Employee.name' => $this->account))) > 0)
			$this->permissions[] = 'employee';

		$this->set('navMenu', $this->Navigation->getTree($this->permissions));
		$this->set('managerInfo', $this->mgr['Manager']);
    }
    
    private function setupMgr($accountName){
	    $this->mgr = $this->Manager->find('first', array('conditions'=> array('Manager.name' => $this->account)));
	    if(!$this->mgr)
		    return false;

	    $this->mgr['Requests'] = array();
	    foreach($this->mgr['Groups'] as &$group){
		    $groupData = $this->Group->find('first', array(
					    'conditions'	=> array('Group.id' => $group['id']),
					    ));
		    if(array_key_exists('Employees',$groupData))
			    $group['Employees'] = $groupData['Employees'];
		    else
			    $group['Employees'] = array();

		    //Get requests of each employee
		    foreach($group['Employees'] as $employee){
			    $requests = $this->Request->find('list', array(
						    'conditions' => array(
							    'Request.employee_id' => $employee['employee_id'],
							    'Request.resolved_by' => NULL,
							    ),
						    'fields' => array(
							    'Request.request_id'
							    ),
						    ));
		    $this->mgr['Requests'] = array_merge($this->mgr['Requests'],$requests);
		    }
	    }
	    $this->mgr['Requests'] = array_unique($this->mgr['Requests']);
	    return true;
    }

    function index(){
	    //Populate groups with employee lists, get request count
	    $this->set('employeeGroups', $this->mgr['Groups']);
	    $this->set('requestCount', count($this->mgr['Requests']));
	    $this->set('debug', $this->mgr);
    }

    //present hours for target week, for target employee
    function hours($empId = null,$weekId = 0){
	    $emp = $this->Employee->find('first', array('conditions'=> array('Employee.employee_id' => $empId)));
	    //verfiy employee exists and manager has authority over employee
	    if(!$emp)
		    $this->redirect('/Manager/index');
	    $validGrpIds = array();
	    foreach($emp['Groups'] as $group)
	    {
	    	$validGrpIds[$group['id']] = false;
	    }
	    foreach(array_values($this->mgr['Groups']) as $index=>$group)
	    {
	    	if(array_key_exists($group['id'], $validGrpIds))
			break;
		else if($index+1 == count($this->mgr['Groups']))
			$this->redirect('/Manager/index');
	    }
	    //determine start and end dates of target week
	    $currentWeekStart = date('Y-m-d', strtotime('Monday this week'));
	    $lowerTimeBound = date('Y-m-d', (strtotime($currentWeekStart) - $weekId*(7 * 24 * 60 * 60)));
	    $upperTimeBound = date('Y-m-d', (strtotime($lowerTimeBound)+(7*24*60*60)));
	    $conditions =  array(
			    "Hour.date >=" => $lowerTimeBound,
			    "Hour.date <" => $upperTimeBound,
			    "Hour.employee_id " => $emp['Employee']['employee_id'],
			    "Hour.replaced_by"=>null
			    );
	    $hours = $this->Hour->find('all',array('conditions'=>$conditions,'order'=>array('Hour.date ASC')));
	    $total = 0;
	    $in;
	    $out;
	    $state = 0;

	    //calculate total logged hours for the target week
	    foreach($hours as &$hour){
		    if($state==0){
			    if(!empty($hour['Hour']['clock_in'])){
				    $state=1;
				    $in = $this->Hour->ClosestQuarter($hour['Hour']['date']);
			    }
		    }
		    else{
			    if(!empty($hour['Hour']['clock_in'])){
				    $in = $this->Hour->ClosestQuarter($hour['Hour']['date']);
			    }
			    else{
				    $out = $this->Hour->ClosestQuarter($hour['Hour']['date']);
				    $total+= (($out-$in)/3600);
				    $state=0;
			    }
		    }
		    $hour['Hour']['created_by'] = $this->getName($hour['Hour']['created_by']);
		    $hour['Hour']['proj_name'] = $this->getProjectName($hour['Hour']['proj_id']);
		    $hour['Hour']['date'] = date('r',($this->Hour->ClosestQuarter($hour['Hour']['date'])));
	    }

	    //$total = intval(floor($total));
	    $this->set('upper',date('m-d-Y',strtotime($upperTimeBound)));
	    $this->set('lower',date('m-d-Y',strtotime($lowerTimeBound)));
	    $this->set('total',$total);
	    $this->set('hours',$hours);
	    $this->set('weekId',$weekId);
	    $this->set('employee', $emp);
    }

    function clock(){
        if ($this->request->is('post'))
        {
            echo "<script language>alert('2')</script>";
            $clockIn = $this->request->data['employee']['clock_in'];
            $empID= $this->request->data['employee']['employee_id'];
            $projID= $this->request->data['employee']['proj_id'];
            var_dump(get_defined_vars());
	    //create new hour entry using data received from view
            if ($this->Employee->clock($clockIn,$empID,$projID))
            {
                echo "<script language>alert('success')</script>";
                $this->redirect(array('action' => 'index'));
            }
            else
            {
                echo "<script language>alert('There was a problem')</script>";
            }
        } 
    }

    //sends all requests to the view
    function reviewrequests(){
        $reqs = $this->Request->find('all');
        $this->set('requests',$reqs);
    }

    function approveRequest($request_id = null)
    {
        if ($request_id != null)
        {
            $reqs = $this->Request->find('first',array(
                'conditions' => array('Request.request_id' => $request_id) 
            ));
            $originalHour = $this->Hour->find('first',array(
                'conditions' => array('Hour.trans_id' => $reqs['Request']['replaces']) 
            ));
             $this->set('request',$reqs);
             $this->set('originalHour',$originalHour);
            
        } 
    }

    function currentlyworking(){
	$working = array();
	$emps = $this->Employee->find('all');
	foreach($emps as $emp){
		if($this->Employee->currentlyIn($emp['Employee']['employee_id'])){
			$working[] = $emp;
		}
	}
	$this->set('emps',$working);
    }
    //set request as denied, does not create new hour entry
    function deny($request_id = null)
    {
    if ($request_id != null)
        {
            $reqs = $this->Request->find('first',array(
                'conditions' => array('Request.request_id' => $request_id) 
            ));

            $reqs['Request']['approved'] = false;
            $this->Request->Save($reqs);

            $this->redirect(array(
                'controller' => 'Manager',
                'action' => 'reviewrequests'
            ));

        }

    }
    //marks request as approved, creates new hour entry
    function approve($request_id = null)
    {
        if ($request_id != null)
        {
            $reqs = $this->Request->find('first',array(
                'conditions' => array('Request.request_id' => $request_id) 
            ));
	    $transid = $reqs['Request']['replaces'];
	    $oldhour = $this->Hour->find('first', array('conditions'=>array('Hour.trans_id'=>$transid)));
            $manager = $this->Manager->find('first', array(
                 'conditions' => array('Manager.name' => $this->account)
            ));
            
            $manager_id = $manager['Manager']['manager_id'];
            
            //create new hour entry
            $newhour = $this->Hour->Save(array(
                'created_by' => $reqs['Request']['employee_id'],
                'clock_in' => $reqs['Request']['clock_in'],
                'employee_id' => $reqs['Request']['employee_id'],
                'proj_id' => $reqs['Request']['proj_id'],
                'replaces' => $reqs['Request']['replaces'],
                'date' => $reqs['Request']['date']
            ));
	    //flag old entry as no longer valid
	    $oldhour['Hour']['replaced_by'] = $newhour['Hour']['trans_id'];

            $reqs['Request']['approved'] = true;
            $reqs['Request']['resolved_by']  = $manager_id;
            $this->Request->Save($reqs);
	    $this->Hour->Save($oldhour);


            $this->Error->error;
          $this->redirect(array(
              'controller' => 'Manager',
              'action' => 'reviewrequests'
          ));

        }
    }
    //returns the name of an employee or manager
    private function getName($ID){
        $countEmployee= $this->Employee->find('first',array('conditions'=>
            array('Employee.employee_id' => $ID)
        ));
        $name = '';
        if( $countEmployee > 0){
            $employee = $this->Employee->find('first',array('conditions'=>
                array('Employee.employee_id' => $ID)
            ));
            $name = $employee['Employee']['name'];
        }
        else{
             $manager= $this->Manager->find('first',array('conditions'=>
                array('Manager.manager_id' => $ID)
            ));
            $name = $manager['Manager']['name'];

        }
        return $name;
    }
    //returns the description of a project
    public function getProjectName($projID){
        $count = $this->Project->find('count',array('conditions'=>
            array('Project.project_id' => $projID)
        ));
        $name = $projID; //default response
        if ($count > 0){
            $project= $this->Project->find('first',array('conditions'=>
                array('Project.project_id' => $projID)
            ));
            $name = $project['Project']['description'];
        }
        return $name;
    }

    public function edithour($trans_id = null)
    {
	    //Populate groups with employee lists
	    foreach($this->mgr['Groups'] as &$group){
	    	$groupData = $this->Group->find('first', array(
			'conditions'	=> array('Group.id' => $group['id']),
		));
		if(array_key_exists('Employees',$groupData))
			$group['Employees'] = $groupData['Employees'];
		else
			$group['Employees'] = array();
	
	    }

	    $this->set('employeeGroups', $this->mgr['Groups']);


       	$manager=$this->Manager->find('first', array('conditions'=> array('Manager.name' => $this->account)));
        $manager_id = $manager['Manager']['manager_id'];
        if($manager_id == null)
        {
            $this->set('gtAccount',NULL);
        }
        $this->loadModel('ProjectMember');
        if ($trans_id != null)
        {
            $hour = $this->Hour->find('first', array('conditions'=>
                array('Hour.trans_id' => $trans_id)
            ));
            $this->set('replaceHour',$hour);
            //set projects variable for the employee
            $employee_id = $hour['Hour']['employee_id'];
            $projectMembers = $this->ProjectMember->find('all', array('conditions'=>
                array('ProjectMember.employee_id' => $employee_id)
            ));
            $projects = array();
            foreach($projectMembers as $projectMember):
                $projects[] = $this->Project->find('all',array('conditions'=>
                array('Project.project_id' => $projectMember['ProjectMember']['project_id'])
            ));
            endforeach;
            $cleanProjects = array();
            foreach($projects as $project):
                foreach($project as $proj):
                    $cleanProjects[] = $proj;
                endforeach;
            endforeach;
            $this->set('projects',$cleanProjects);
        }
        else{
            $this->set('replaceHour',null);
            $projects = $this->Project->find('all');
            $this->set('projects',$projects);
        }
        if ($this->request->is('post'))
        {
            if ($this->Request->Save(array(
                'clock_in' => $this->request->data['Hour']['clock_in'], 
                'employee_id' => $this->request->data['Hour']['employee_id'], 
                'replaces' => $this->request->data['Hour']['replaces'], 
                'proj_id' => $this->request->data['Hour']['proj_id'], 
                'comment' => $this->request->data['Hour']['comment'], 
                'resolved_by' => $manager_id,
                'approved' => true,
                'date' => $this->request->data['Hour']['datetime']
                ))
            )
            {
                if ($this->Hour->Save(array(
                    'clock_in' => $this->request->data['Hour']['clock_in'], 
                    'employee_id' => $this->request->data['Hour']['employee_id'], 
                    'replaces' => $this->request->data['Hour']['replaces'], 
                    'proj_id' => $this->request->data['Hour']['proj_id'], 
                    'date' => $this->request->data['Hour']['datetime'],
                    'created_by' => $manager_id
                    )
                ))
                {
		    if($this->request->data['Hour']['replaces']!=null){
			$replaces = $this->request->data['Hour']['replaces'];
			$oldHour = $this->Hour->find('first', array('conditions'=>array('Hour.trans_id'=>$replaces)));
			$oldHour['Hour']['replaced_by'] = -1;
			$this->Hour->Save($oldHour);
                    $this->redirect(array('action' => 'index'));
		}
                }
                else
                {
                    echo "<script language>alert('The hour didn\'t ".
                        "save but the request did')</script>";
                }
            }
            else
            {
                echo "<script language>alert('There was a problem')</script>";
            }
        }
    }


}
?>
